package com.cug.nageoffer.user.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cug.nageoffer.model.entity.User;
import com.cug.nageoffer.model.vo.LoginVo;
import com.cug.nageoffer.model.vo.Result;
import com.cug.nageoffer.model.vo.ResultCodeEnum;
import com.cug.nageoffer.user.config.MinioConfiguration;
import com.cug.nageoffer.user.mapper.UserMapper;
import com.cug.nageoffer.user.service.UserService;
import com.cug.nageoffer.util.AuthContextUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

    @Resource
    private RBloomFilter<String> userRegisterCachePenetrationBloomFilter;

    @Resource
    private MinioConfiguration minioConfiguration;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 用户注册
     */
    @Override
    public Result<String> register(User userDO) {
        System.err.println(userDO);
        boolean exist = userRegisterCachePenetrationBloomFilter.contains(userDO.getUsername());
        if(exist){
            log.error("用户名已存在！");
            return Result.build(null, ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
//        userDO.setCreateTime(DateTime.now());
        try {
            save(userDO);
            userRegisterCachePenetrationBloomFilter.add(userDO.getUsername());
        }
        catch (Throwable e){
            log.error("Something went wrong?");
            return Result.build(null,ResultCodeEnum.OPERATION_ERROR);
        }
        return Result.build(null,ResultCodeEnum.SUCCESS);
    }

    /**
     * 用户登录
     */
    @Override
    public LoginVo login(User userDO) {
        User user = query().eq("username", userDO.getUsername()).eq("password", userDO.getPassword()).eq("del_flag",0).one();
        if(user==null){
            return null;
        }
        // 生成token，保存到redis
        String token = UUID.randomUUID().toString().replaceAll("-", "");

        stringRedisTemplate.opsForValue().set("user:nageoffer:login:"+token,JSONUtil.toJsonStr(user),1, TimeUnit.DAYS);
        return LoginVo.builder().token(token).build();
    }

    /**
     * 查询用户信息
     */
    @Override
    public User queryInfo(String username) {
        try{
            User user = query().eq("username", username).eq("del_flag", 0).one();
            log.info("获取到用户信息：{}", user);
            return user;
        }catch (Exception e){
            log.error(Arrays.toString(e.getStackTrace()));
            return null;
        }
    }

    /**
     * 用户退出登录
     */
    @Override
    public Boolean logout(User userDO) {
        User user = query().eq("username", userDO.getUsername()).eq("password", userDO.getPassword()).eq("del_flag",0).one();
        if(user==null){
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

    /**
     * 修改用户信息
     */
    @Override
    public Result<String> modifyInfo(User userDO) {
        User user = query().eq("id", userDO.getId()).eq("del_flag", 0).one();
        if(user == null){
            save(userDO);
        }
        else {
            String jsonStr = JSONUtil.toJsonStr(userDO);
            stringRedisTemplate.opsForValue().set("user:nageoffer:login:"+AuthContextUtil.get().getToken(),jsonStr);
            update().eq("id",userDO.getId()).update(userDO);
        }
        return Result.build(null,ResultCodeEnum.SUCCESS);
    }

    /**
     * 上传用户头像
     */
    @Override
    public Result<String> uploadProfile(MultipartFile multipartFile) throws Exception {
        String filePath = minioConfiguration.putObject(multipartFile,"headImage/");
        update().eq("id", AuthContextUtil.get().getId()).set("profile",filePath).update();
        return Result.build(null,ResultCodeEnum.SUCCESS);
    }

    /**
     * 修改用户求职状态
     */
    @Override
    public Result<String> modifyStatus(Integer status) {
        log.info("修改用户状态，id：{}",AuthContextUtil.get().getId());
        update().eq("id", AuthContextUtil.get().getId()).set("status",status).update();
        return Result.build(null,ResultCodeEnum.SUCCESS);
    }

    @Override
    public String getUsername(Long id) {
        User user = query().eq("id", id).one();
        return user.getUsername();
    }
}
